//
//  DR_LookPDFVC.swift
//  DocReaderRP
//
//  Created by  mac on 2025/11/14.
//

import UIKit
import PDFKit
import SnapKit
import Toast_Swift

class DR_LookPDFVC: DR_BaseVC {

    private var pdfModel: DR_PDFFileModel?
    private var pdfDocument: PDFDocument?
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
        setupConstraints()
        
        backButton.addTarget(self, action: #selector(clickBackButton), for: .touchUpInside)
        moreButton.addTarget(self, action: #selector(clickMoreButton), for: .touchUpInside)
    }
    
    // MARK: - 配置 PDF 文件
    func configure(with pdfModel: DR_PDFFileModel, isPasswordVerified: Bool = false) {
        self.pdfModel = pdfModel
        nameLabel.text = pdfModel.displayName
        
        // 如果已经在外部验证过密码，直接加载PDF
        // 否则检查是否有密码
        if isPasswordVerified {
            // 已经验证过密码，直接加载 PDF
            loadPDFDocument()
        } else if DR_PDFTool.shared.hasPassword(for: pdfModel.fileURL) {
            // 显示输入密码弹窗
            showPasswordInputSheet()
        } else {
            // 直接加载 PDF
            loadPDFDocument()
        }
    }
    
    // MARK: - 显示输入密码弹窗
    private func showPasswordInputSheet() {
        guard let pdfModel = pdfModel else { return }
        
        let passwordSheet = DR_EnterPasswordSheet()
        
        // 配置文件信息
        passwordSheet.configure(fileName: pdfModel.fileName, fileSize: pdfModel.fileSizeString)
        
        passwordSheet.onConfirm = { [weak self, weak passwordSheet] password in
            guard let self = self, let pdfModel = self.pdfModel, let sheet = passwordSheet else { return }
            
            // 验证密码
            if DR_PDFTool.shared.verifyPassword(for: pdfModel.fileURL, password: password) {
                // 密码正确，关闭弹窗并加载 PDF
                sheet.hide()
                self.loadPDFDocument()
            } else {
                // 密码错误，显示错误信息（不关闭弹窗）
                sheet.showError()
            }
        }
        
        passwordSheet.onCancel = { [weak self] in
            // 取消操作，返回上一页
            self?.navigationController?.popViewController(animated: true)
        }
        
        // 显示密码输入弹窗
        if let window = UIApplication.shared.keyWindowCompat {
            passwordSheet.show(in: window)
        } else {
            passwordSheet.show(in: view)
        }
    }
    
    // MARK: - 加载 PDF 文档
    private func loadPDFDocument() {
        guard let pdfModel = pdfModel else { return }
        
        if let pdfDoc = DR_PDFTool.shared.getPDFDocument(fileURL: pdfModel.fileURL) {
            self.pdfDocument = pdfDoc
            loadPDFView()
        }
    }
    
    @objc private func clickBackButton(){
        self.navigationController?.popViewController(animated: true)
    }
    
    @objc private func clickMoreButton(){
        guard let pdfModel = pdfModel else { return }
        
        // 将 DR_PDFFileModel 转换为 DR_FileModel
        let fileModel = DR_FileModel(from: pdfModel)
        showMoreActionSheet(for: fileModel)
    }
    
    // MARK: - 显示更多选项弹窗
    private func showMoreActionSheet(for fileModel: DR_FileModel) {
        let actionSheet = DR_FileMoreActionSheet()
        
        // 将 DR_FileModel 转换为 DR_SearchFileModel
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd"
        let dateString = dateFormatter.string(from: fileModel.createDate)
        
        // 检查收藏状态（使用全局收藏管理器）
        let isFavorite = DR_FileManager.shared.isFavorite(fileModel)
        
        let searchFileModel = DR_SearchFileModel(
            fileName: fileModel.displayName,
            date: dateString,
            size: fileModel.fileSizeString,
            isFavorite: isFavorite,
            fileType: fileModel.fileType.rawValue
        )
        
        // 根据文件类型决定显示哪些操作
        var actions: [DR_FileMoreAction] = []
        
        // PDF 特有操作
        if fileModel.fileType == .pdf {
            actions.append(DR_FileMoreAction(title: "home_merge".localized, iconName: "more_merge", action: { [weak self] in
                self?.handleMergePDF()
            }))
            actions.append(DR_FileMoreAction(title: "home_split".localized, iconName: "more_split", action: { [weak self] in
                self?.handleSplitPDF(fileModel)
            }))
            
            // 根据是否已设置密码显示不同的操作
            let lockTitle = DR_PDFTool.shared.hasPassword(for: fileModel.fileURL) ? "Unlock PDF" : "home_lock".localized
            actions.append(DR_FileMoreAction(title: lockTitle, iconName: "more_lock", action: { [weak self] in
                self?.handleLockPDF(fileModel)
            }))
        }
        
        // 通用操作
        actions.append(DR_FileMoreAction(title: "more_rename".localized, iconName: "more_rename", shouldAutoHide: false, action: { [weak self, unowned actionSheet] in
            actionSheet.hide()
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                self?.handleRenameFile(fileModel)
            }
        }))
        // 根据收藏状态设置不同的标题和图标
        let favoriteTitle = isFavorite ? "more_collected".localized : "more_collection".localized
        let favoriteIcon = isFavorite ? "home_collected" : "home_collect"
        actions.append(DR_FileMoreAction(title: favoriteTitle, iconName: favoriteIcon, action: { [weak self] in
            self?.handleToggleFavorite(fileModel)
        }))
        actions.append(DR_FileMoreAction(title: "more_share".localized, iconName: "more_share", action: { [weak self] in
            self?.handleShareFile(fileModel)
        }))
        actions.append(DR_FileMoreAction(title: "more_details".localized, iconName: "more_detail", action: { [weak self] in
            self?.handleShowDetails(fileModel)
        }))
        actions.append(DR_FileMoreAction(title: "more_delete".localized, iconName: "more_del", action: { [weak self] in
            self?.handleDeleteFile(fileModel)
        }))
        
        actionSheet.configure(with: searchFileModel, actions: actions)
        
        // 确保显示在 window 或 tabBarController 的 view 上
        if let window = UIApplication.shared.keyWindowCompat {
            actionSheet.show(in: window)
        } else if let tabBarController = self.tabBarController {
            actionSheet.show(in: tabBarController.view)
        } else {
            actionSheet.show(in: view)
        }
    }
    
    // MARK: - 处理重命名
    private func handleRenameFile(_ fileModel: DR_FileModel) {
        let renameSheet = DR_RenameSheet()
        renameSheet.configure(with: fileModel.displayName)
        
        renameSheet.onConfirm = { [weak self] newName in
            guard let self = self else { return }
            
            // PDF文件使用DR_PDFTool重命名
            if fileModel.fileType == .pdf {
                if let newPDFModel = DR_PDFTool.shared.renamePDF(oldFileURL: fileModel.fileURL, newName: newName) {
                    // 更新当前PDF模型
                    self.pdfModel = newPDFModel
                    self.nameLabel.text = newPDFModel.displayName
                    // 重新加载PDF
                    self.loadPDFDocument()
                    self.view.makeToast("renamed_succ".localized, duration: 2.0, position: .center)
                } else {
                    self.view.makeToast("renamed_error".localized, duration: 2.0, position: .center)
                }
            } else {
                // 其他文件类型的重命名
                if let newURL = self.renameFile(oldFileURL: fileModel.fileURL, newName: newName) {
                    // 创建新的文件模型并重新加载
                    let newFileModel = DR_FileModel(fileURL: newURL)
                    let newPDFModel = DR_PDFFileModel(
                        fileName: newFileModel.fileName,
                        fileURL: newFileModel.fileURL,
                        fileSize: newFileModel.fileSize,
                        createDate: newFileModel.createDate,
                        pageCount: newFileModel.pageCount
                    )
                    self.pdfModel = newPDFModel
                    self.nameLabel.text = newPDFModel.displayName
                    self.loadPDFDocument()
                    self.view.makeToast("renamed_succ".localized, duration: 2.0, position: .center)
                } else {
                    self.view.makeToast("renamed_error".localized, duration: 2.0, position: .center)
                }
            }
        }
        
        renameSheet.onCancel = {
            // 取消操作，不需要处理
        }
        
        // 确保显示在 window 或 tabBarController 的 view 上
        if let window = UIApplication.shared.keyWindowCompat {
            renameSheet.show(in: window)
        } else if let tabBarController = self.tabBarController {
            renameSheet.show(in: tabBarController.view)
        } else {
            renameSheet.show(in: view)
        }
    }
    
    // MARK: - 重命名文件（通用）
    private func renameFile(oldFileURL: URL, newName: String) -> URL? {
        let fileExtension = oldFileURL.pathExtension
        let sanitizedName = sanitizeFileName(newName)
        let newURL = oldFileURL.deletingLastPathComponent().appendingPathComponent("\(sanitizedName).\(fileExtension)")
        
        // 检查新文件名是否已存在
        if FileManager.default.fileExists(atPath: newURL.path) {
            return nil
        }
        
        // 重命名文件
        do {
            try FileManager.default.moveItem(at: oldFileURL, to: newURL)
            return newURL
        } catch {
            print("❌ [DR_LookPDFVC] 文件重命名失败: \(error.localizedDescription)")
            return nil
        }
    }
    
    // MARK: - 清理文件名
    private func sanitizeFileName(_ fileName: String) -> String {
        let invalidChars = CharacterSet(charactersIn: "/\\?%*|\"<>")
        return fileName.components(separatedBy: invalidChars).joined(separator: "_")
    }
    
    // MARK: - 处理收藏切换
    private func handleToggleFavorite(_ fileModel: DR_FileModel) {
        let isNowFavorite = DR_FileManager.shared.toggleFavorite(fileModel)
        if isNowFavorite {
            view.makeToast("collect_succ".localized, duration: 2.0, position: .center)
        } else {
            view.makeToast("collect_error".localized, duration: 2.0, position: .center)
        }
    }
    
    // MARK: - 处理分享
    private func handleShareFile(_ fileModel: DR_FileModel) {
        let activityVC = UIActivityViewController(activityItems: [fileModel.fileURL], applicationActivities: nil)
        
        if let popover = activityVC.popoverPresentationController {
            popover.sourceView = view
            popover.sourceRect = CGRect(x: view.bounds.midX, y: view.bounds.midY, width: 0, height: 0)
            popover.permittedArrowDirections = []
        }
        
        present(activityVC, animated: true)
    }
    
    // MARK: - 处理显示详情
    private func handleShowDetails(_ fileModel: DR_FileModel) {
        let detailsSheet = DR_FileDetailsSheet()
        detailsSheet.configure(with: fileModel)
        
        // 确保显示在 window 或 tabBarController 的 view 上
        if let window = UIApplication.shared.keyWindowCompat {
            detailsSheet.show(in: window)
        } else if let tabBarController = self.tabBarController {
            detailsSheet.show(in: tabBarController.view)
        } else {
            detailsSheet.show(in: view)
        }
    }
    
    // MARK: - 处理锁定/解锁 PDF
    private func handleLockPDF(_ fileModel: DR_FileModel) {
        if DR_PDFTool.shared.hasPassword(for: fileModel.fileURL) {
            // 已设置密码，先验证密码再解锁
            let passwordSheet = DR_EnterPasswordSheet()
            
            // 配置文件信息
            passwordSheet.configure(fileName: fileModel.fileName, fileSize: fileModel.fileSizeString)
            
            passwordSheet.onConfirm = { [weak self, weak passwordSheet] password in
                guard let self = self, let sheet = passwordSheet else { return }
                
                // 验证密码
                if DR_PDFTool.shared.verifyPassword(for: fileModel.fileURL, password: password) {
                    // 密码正确，移除密码
                    if DR_PDFTool.shared.removePassword(for: fileModel.fileURL) {
                        sheet.hide()
                        self.view.makeToast("密码已移除", duration: 2.0, position: .center)
                    } else {
                        self.view.makeToast("操作失败", duration: 2.0, position: .center)
                    }
                } else {
                    // 密码错误，显示错误信息（不关闭弹窗）
                    sheet.showError()
                }
            }
            
            passwordSheet.onCancel = {
                // 取消操作，不需要处理
            }
            
            // 确保显示在 window 或 tabBarController 的 view 上
            if let window = UIApplication.shared.keyWindowCompat {
                passwordSheet.show(in: window)
            } else if let tabBarController = self.tabBarController {
                passwordSheet.show(in: tabBarController.view)
            } else {
                passwordSheet.show(in: view)
            }
        } else {
            // 未设置密码，显示设置密码弹窗
            let passwordSheet = DR_SetPasswordSheet()
            
            passwordSheet.onConfirm = { [weak self] password in
                guard let self = self else { return }
                if DR_PDFTool.shared.setPassword(for: fileModel.fileURL, password: password) {
                    self.view.makeToast("密码设置成功", duration: 2.0, position: .center)
                } else {
                    self.view.makeToast("密码设置失败", duration: 2.0, position: .center)
                }
            }
            
            passwordSheet.onCancel = {
                // 取消操作，不需要处理
            }
            
            // 确保显示在 window 或 tabBarController 的 view 上
            if let window = UIApplication.shared.keyWindowCompat {
                passwordSheet.show(in: window)
            } else if let tabBarController = self.tabBarController {
                passwordSheet.show(in: tabBarController.view)
            } else {
                passwordSheet.show(in: view)
            }
        }
    }
    
    // MARK: - 处理Merge PDF
    private func handleMergePDF() {
        let selVC = DR_SelectVC()
        selVC.type = 1
        pushHidingTabBar(selVC, animated: true)
    }
    
    // MARK: - 处理Split PDF
    private func handleSplitPDF(_ fileModel: DR_FileModel) {
        // 检查PDF是否被锁定
        if DR_PDFTool.shared.hasPassword(for: fileModel.fileURL) {
            // PDF已锁定，需要先输入密码
            let passwordSheet = DR_EnterPasswordSheet()
            passwordSheet.configure(fileName: fileModel.fileName, fileSize: fileModel.fileSizeString)
            
            passwordSheet.onConfirm = { [weak self, weak passwordSheet] password in
                guard let self = self, let sheet = passwordSheet else { return }
                if DR_PDFTool.shared.verifyPassword(for: fileModel.fileURL, password: password) {
                    sheet.hide()
                    DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                        self.openSplitPDFVC(fileModel.fileURL)
                    }
                } else {
                    sheet.showError()
                }
            }
            
            passwordSheet.onCancel = {}
            
            if let window = UIApplication.shared.keyWindowCompat {
                passwordSheet.show(in: window)
            } else if let tabBarController = self.tabBarController {
                passwordSheet.show(in: tabBarController.view)
            } else {
                passwordSheet.show(in: view)
            }
        } else {
            // PDF未锁定，直接打开Split页面
            openSplitPDFVC(fileModel.fileURL)
        }
    }
    
    private func openSplitPDFVC(_ fileURL: URL) {
        let splitVC = DR_SplitPDFVC(pdfFileURL: fileURL)
        pushHidingTabBar(splitVC, animated: true)
    }
    
    // MARK: - 处理删除
    private func handleDeleteFile(_ fileModel: DR_FileModel) {
        let deleteSheet = DR_DeleteConfirmSheet()
        
        deleteSheet.onDelete = { [weak self] in
            guard let self = self else { return }
            do {
                // 删除前先移除收藏
                DR_FileManager.shared.removeFavorite(fileModel)
                try FileManager.default.removeItem(at: fileModel.fileURL)
                self.view.makeToast("del_succ".localized, duration: 2.0, position: .center)
                // 删除成功后返回上一页
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                    self.navigationController?.popViewController(animated: true)
                }
            } catch {
                self.view.makeToast("del_error".localized, duration: 2.0, position: .center)
            }
        }
        
        deleteSheet.onCancel = {
            // 取消操作，不需要处理
        }
        
        // 确保显示在 window 或 tabBarController 的 view 上
        if let window = UIApplication.shared.keyWindowCompat {
            deleteSheet.show(in: window)
        } else if let tabBarController = self.tabBarController {
            deleteSheet.show(in: tabBarController.view)
        } else {
            deleteSheet.show(in: view)
        }
    }
    
    private func setupUI(){
        
        view.addSubview(backButton)
        view.addSubview(nameLabel)
        view.addSubview(moreButton)
        view.addSubview(pdfView)
    }
    
    private func setupConstraints(){
        
        backButton.snp.makeConstraints { make in
            make.leading.equalToSuperview()
            make.top.equalTo(view.safeAreaLayoutGuide)
            make.width.equalTo(56)
            make.height.equalTo(44)
        }
        moreButton.snp.makeConstraints { make in
            make.trailing.equalToSuperview().offset(-12)
            make.centerY.equalTo(backButton)
            make.width.height.equalTo(30)
        }
        nameLabel.snp.makeConstraints { make in
            make.leading.equalTo(backButton.snp.trailing)
            make.trailing.equalTo(moreButton.snp.leading).offset(-10)
            make.centerY.equalTo(backButton)
        }
        
        pdfView.snp.makeConstraints { make in
            make.leading.trailing.bottom.equalToSuperview()
            make.top.equalTo(backButton.snp.bottom)
        }
    }
    
    // MARK: - 加载 PDF 视图
    private func loadPDFView() {
        guard let pdfDocument = pdfDocument else { return }
        pdfView.document = pdfDocument
        pdfView.autoScales = true
        pdfView.displayMode = .singlePageContinuous
        pdfView.displayDirection = .vertical
    }

    private let backButton: UIButton = {
        let v = UIButton(type: .custom)
        v.setImage("common_back".toImage, for: .normal)
        return v
    }()
    private let moreButton: UIButton = {
        let v = UIButton(type: .custom)
        v.setImage("common_more".toImage, for: .normal)
        return v
    }()
    private let nameLabel: UILabel = {
        let v = UILabel()
        v.textColor = .black
        v.font = UIFont.systemFont(ofSize: 16)
        v.textAlignment = .left
        return v
    }()
    
    private let pdfView: PDFView = {
        let view = PDFView()
        view.backgroundColor = .systemGray6
        return view
    }()
}
